package com.fh.common.distributedlock;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.fh.common.api.vo.Result;
import com.fh.common.util.UUIDGeneratorUtils;

/**
 *  jedis分布式锁切面类
 * @author junqiu
 *
 */
//@Aspect
//@Component
public class JedisLockAspect {

	@Autowired
	private JedisLockTool jedisLockTool;
	@Pointcut("@annotation(com.fh.common.distributedlock.JedisLock)")
	public void lockPointCut() {
		
	}
	
	@Around("lockPointCut()")
	public Object around(ProceedingJoinPoint point) throws Throwable{
		String requestId=UUIDGeneratorUtils.getUUID();
		String classSimpleName=point.getTarget().getClass().getName();
		MethodSignature methodSignature=(MethodSignature)point.getSignature();
		Method method=methodSignature.getMethod();
		JedisLock jedisLock=method.getAnnotation(JedisLock.class);
		int timeout=jedisLock.timeout();
		Object[] args=point.getArgs();
		Object params=JSON.toJSON(args);
		String lockKey=classSimpleName+":"+method.getName()+":"+params.toString();
		if(jedisLockTool.tryGetDistributedLock(lockKey, requestId,timeout)) {
			try {
				Object result = point.proceed();
				return result;
			} catch (Exception e) {
				throw e;
			}finally {
				jedisLockTool.releaseDistributedLock(lockKey, requestId);
			}
		}
		else {
			return Result.error("网络阻塞，请稍后再试");
		}
	}
}
